package com.pilipili.serverapi.collection.service;

import com.pilipili.common.Exception.CommonErrorCode;
import com.pilipili.common.controller.PageCommResult;
import com.pilipili.common.service.AbstractService;
import com.pilipili.common.util.BeanUtils;
import com.pilipili.serverapi.collection.dto.req.FavoritesWithIdDto;
import com.pilipili.serverapi.collection.dto.resp.FavoritesResultDto;
import com.pilipili.serverapi.collection.entity.Favorites;
import com.pilipili.serverapi.collection.repository.FavoritesRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 收藏夹管理Service
 *
 * @author chen.guosheng
 */
@Service
public class FavoritesService extends AbstractService<FavoritesRepository, Favorites, Long> {

    @Transactional(readOnly = true)
    public PageCommResult<FavoritesResultDto> search(Long userId, int currentPage, int pageCount) {
        Pageable page = new PageRequest(currentPage, pageCount, Sort.Direction.DESC, "createTime");
        List<Favorites> favoritess = this.repository.findByUserId(userId, page);
        List<FavoritesResultDto> favoritesResultDtos = new ArrayList<FavoritesResultDto>();
        favoritess.forEach(favorites -> favoritesResultDtos.add(new FavoritesResultDto(favorites.getId(), favorites.getUserId(), favorites.getFavoritesName(), favorites.getIntroduction(), favorites.getCreateTime().toString())));
        Long total = this.repository.countByUserId(userId);
        return PageCommResult.successPageResult(favoritesResultDtos, currentPage, pageCount, total);
    }

    @Transactional
    @Override
    public <FavoritesWithIdDto> Favorites editAfterFind(Long id, FavoritesWithIdDto dto, CommonErrorCode errorCode){
        Favorites favorites = this.find(id, errorCode);
        BeanUtils.copyProperties(dto, favorites);
        favorites.setCreateTime(new Date());
        return this.repository.save(favorites);
    }

    /**
     * 批量删除收藏夹
     *
     * @param favoritesIds
     */
    @Transactional
    public void batchDelete(List<Long> favoritesIds) {
        this.repository.deleteByIdIn(favoritesIds);
    }
}
